package com.sky.controller.admin;

import com.sky.dto.SetmealDTO;
import com.sky.dto.SetmealPageQueryDTO;
import com.sky.exception.BaseException;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.SetmealService;
import com.sky.vo.SetmealVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 套餐管理
 */
@RestController
@RequestMapping("/admin/setmeal")
@Api(tags = "套餐相关接口")
@Slf4j
public class SetmealController {

    @Autowired
    private SetmealService setmealService;

    /**
     * 新增套餐
     *
     * @param setmealDTO
     * @return
     */
    @CacheEvict(cacheNames = "setmeal", key = "#setmealDTO.categoryId")
    @PostMapping
    @ApiOperation("新增套餐")
    public Result save(@RequestBody SetmealDTO setmealDTO) {
        if (setmealDTO == null){
            throw new BaseException(400, "参数错误");
        }
        if (setmealDTO.getName() == null){
            throw new BaseException(400, "name不能为空");
        }
        if (setmealDTO.getPrice() == null){
            throw new BaseException(400, "price不能为空");
        }
        if (setmealDTO.getCategoryId() == null){
            throw new BaseException(400, "categoryId不能为空");
        }
        log.info("新增套餐：{}", setmealDTO);
        setmealService.saveWithDish(setmealDTO);
        return Result.success();
    }

    /**
     * 套餐分页查询
     *
     * @param setmealPageQueryDTO
     * @return
     */
    @GetMapping("/page")
    @ApiOperation("套餐分页查询")
    public Result<PageResult> page(SetmealPageQueryDTO setmealPageQueryDTO) {
        Integer page = setmealPageQueryDTO.getPage();
        Integer pageSize = setmealPageQueryDTO.getPageSize();
        if (page == null || page < 0){
            throw new BaseException(400, "page参数有误");
        }

        if (pageSize == null || pageSize < 0){
            throw new BaseException(400, "pageSize参数有误");
        }

        // 1. 校验categoryId格式（若存在）
        if (setmealPageQueryDTO.getCategoryId() != null) {
            // 正则校验：必须是正整数（^[1-9]\\d*$）
            if (!setmealPageQueryDTO.getCategoryId().matches("^[1-9]\\d*$")) {
                throw new BaseException(400, "categoryId为非数字");
            }
            // 2. 转换为Integer，存入categoryIdInt
            try {
                Integer categoryIdInt = Integer.parseInt(setmealPageQueryDTO.getCategoryId());
                setmealPageQueryDTO.setCategoryIdInt(categoryIdInt);
            } catch (NumberFormatException e) {
                // 理论上不会触发（已正则校验），预防意外
                throw new BaseException(400, "categoryId为非数字");
            }
        }

        // 3. 校验status（若存在，假设status只能是0或1）
        if (setmealPageQueryDTO.getStatus() != null) {
            if (setmealPageQueryDTO.getStatus() < 0 || setmealPageQueryDTO.getStatus() > 1) {
                throw new BaseException(400, "status为无效值");
            }
        }

        // 4. 调用Service查询
        log.info("套餐分页查询:{}",setmealPageQueryDTO);
        PageResult pageResult = setmealService.pageQuery(setmealPageQueryDTO);
        return Result.success(pageResult);
    }

    /**
     * 套餐批量删除
     *
     * @param ids
     * @return
     */
    @CacheEvict(cacheNames = "setmeal", allEntries = true)
    @DeleteMapping
    @ApiOperation("批量删除套餐")
    public Result delete(@RequestParam List<Long> ids) {
        if (ids == null || ids.size() == 0){
            throw new BaseException(400, "ids不能为空");
        }
        setmealService.deleteBatch(ids);
        return Result.success();
    }

    /**
     * 根据id查询套餐
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    @ApiOperation("根据id查询套餐")
    public Result<SetmealVO> getById(@PathVariable Long id) {
        SetmealVO setmealVO = setmealService.getByIdWithDish(id);
        return Result.success(setmealVO);
    }

    /**
     * 修改套餐
     *
     * @param setmealDTO
     * @return
     */
    @CacheEvict(cacheNames = "setmeal", allEntries = true)
    @PutMapping
    @ApiOperation("修改套餐")
    public Result update(@RequestBody SetmealDTO setmealDTO) {
        // 传入id不能为空
        if (setmealDTO.getId() == null){
            throw new BaseException(400, "id不能为空");
        }
        // 传入的categoryId不能为空
        if (setmealDTO.getCategoryId() == null){
            throw new BaseException(400, "categoryId不能为空");
        }
        if (setmealDTO.getName() == null){
            throw new BaseException(400, "name不能为空");
        }
        setmealService.update(setmealDTO);
        return Result.success();
    }

    /**
     * 套餐起售停售
     *
     * @param status
     * @param id
     * @return
     */
    @CacheEvict(cacheNames = "setmeal", allEntries = true)
    @PostMapping("/status/{status}")
    @ApiOperation("套餐起售停售")
    public Result startOrStop(@PathVariable Integer status, Long id) {
        // id为空
        if(id == null){
            throw new BaseException(400, "id不能为空");
        }
        // id为0（无效id）
        if(id == 0){
            throw new BaseException(400, "id为无效值");
        }

        setmealService.startOrStop(status, id);
        return Result.success();
    }
}
